package com.siyoumi.mybatispuls.func;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlScriptUtils;
import lombok.SneakyThrows;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

import java.util.LinkedHashMap;

public class FirstMap
        extends AbstractMethod {
    public FirstMap() {
        super("firstMap");
    }

    public FirstMap(String name) {
        super(name);
    }

    @SneakyThrows
    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        String sql = "<script>SELECT %s FROM %s %s %s %s\n</script>";
        String method = "firstMap";

        //join sql
        //String sqlJoin = SqlScriptUtils.convertChoose("sqlJoin != null", "${sqlJoin.getSql}", "");
        String sqlJoin = SqlScriptUtils.convertIf("${ew.getJoinSql}"
                , "@com.siyoumi.component.XApp@isJoinWrpperPlus(ew)", true);

        sql = String.format(sql
                , this.sqlSelectColumns(tableInfo, true)
                //FROM
                , tableInfo.getTableName()
                , sqlJoin
                , this.sqlWhereEntityWrapper(true, tableInfo)
                , this.sqlComment()
                , "LIMIT 1");

        SqlSource sqlSource = this.languageDriver.createSqlSource(this.configuration, sql, modelClass);
        return this.addSelectMappedStatementForOther(mapperClass, method, sqlSource, LinkedHashMap.class);
    }
}
